<template>
  <div class="search_container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 8px">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>书籍管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <!-- 搜索内容和导出区域 -->
      <el-row :gutter="10" style="margin-bottom: 8px">
        <el-row :span="1.3" style="line-height: 40px">
          <span>条件搜索:</span>
        </el-row>
        <el-col :span="3">
          <el-select
            v-model="queryInfo.query"
            filterable
            placeholder="请选择"
            style="margin-left: 15px"
            size="large"
          >
            <el-option
              v-for="item in searchs"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="3">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.condition"
            class="input-with-select"
            @keyup.enter.native="getBookList"
            size="large"
          ></el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" class="el-icon-printer" size="large" @click="getBookList">
            <el-icon><Search /></el-icon>
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="showAddDialog()" size="large">添加书籍</el-button>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="1">
          <el-button type="primary" class="el-icon-printer" size="large" @click="exportToExcel">
            导出Excel
          </el-button>
        </el-col>
        <el-col :span="1"></el-col>
        <el-button size="large" type="success" @click="exportToAll">导出所有图书</el-button>

        <el-col :span="1"></el-col>
        <el-col :span="2" style="float: right">
          <el-button type="warning" @click="AllRemove = true" size="large">
            <i class="el-icon-delete"></i>
            批量删除
          </el-button>
          <el-dialog v-model="AllRemove" title="Tips" width="500">
            <span>确定要删除选定的数据吗？</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="AllRemove = false">取消</el-button>
                <el-button type="primary" @click="removeBatch">确认删除</el-button>
              </div>
            </template>
          </el-dialog>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2" style="float: right">
          <el-button type="success" class="el-icon-full-screen" size="large" @click="fullScreen">
            全屏
          </el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        height="320"
        style="width: 100%"
        id="pdfDom"
        :default-sort="{ prop: 'bookNumber', order: 'ascending' }"
        v-loading="loading"
        show-overflow-tooltip
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        @selection-change="handleSelectionChange"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="BookNumber"
          label="图书编号"
          sortable
          width="110px"
        ></el-table-column>
        <el-table-column prop="BookName" label="书名" width="80px"></el-table-column>
        <el-table-column prop="BookAuthor" label="作者" width="80px"></el-table-column>
        <el-table-column prop="BookLibrary" label="图书馆" width="80px"></el-table-column>
        <el-table-column prop="BookType" label="分类" width="80px"></el-table-column>
        <el-table-column prop="BookLocation" label="位置" sortable width="80px"></el-table-column>
        <el-table-column label="状态" prop="BookStatus" sortable width="80px">
          <!-- <template #default="{ row }">
            {{ row.BookStatus ? "已借出" : "未借出" }}
          </template> -->
        </el-table-column>
        <el-table-column prop="BookDescription" label="描述"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 修改按钮 -->
            <el-button type="primary" @click="showEditDialog(row.BookID)">
              <el-icon><EditPen /></el-icon>
            </el-button>
            <!-- 删除按钮 -->

            <el-button type="danger" @click="removeUserById(row.BookID)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页查询区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 3, 4, 5]"
        :page-size="queryInfo.size"
        layout="total,  prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 修改规则的对话框 -->
      <el-dialog
        title="修改书籍"
        v-model="editDialogVisible"
        width="50%"
        @close="editDialogClosed()"
      >
        <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="120px">
          <el-form-item label="书名" prop="bookName">
            <el-input v-model="editForm.bookName"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="bookAuthor">
            <el-input v-model="editForm.bookAuthor"></el-input>
          </el-form-item>
          <el-form-item label="图书馆">
            <el-radio-group v-model="editForm.bookAuthorookLibrary" size="large">
              <el-radio-button value="南图">南图</el-radio-button>
              <el-radio-button value="北图">北图</el-radio-button>
              <el-radio-button value="教师之家">教师之家</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="editForm.bookType" placeholder="请选择">
              <el-option
                v-for="item in types"
                :key="item.TypeID"
                :label="item.TypeName"
                :value="item.TypeID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="bookLocation">
            <el-radio-group v-model="editForm.bookLocation">
              <el-radio-button value="馆藏区A">馆藏区A</el-radio-button>
              <el-radio-button value="馆藏区B">馆藏区B</el-radio-button>
              <el-radio-button value="馆藏区C">馆藏区C</el-radio-button>
              <el-radio-button value="馆藏区D">馆藏区D</el-radio-button>
              <el-radio-button value="馆藏区E">馆藏区E</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="bookStatus">
            <el-radio-group v-model="editForm.bookStatus">
              <el-radio value="借出">借出</el-radio>
              <el-radio value="在馆">在馆</el-radio>
              <el-radio value="维修">维修</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="书籍简介" prop="bookDescription">
            <el-input type="textarea" v-model="editForm.bookDescription"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateBook()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加书籍的对话框 -->
      <el-dialog title="添加书籍" v-model="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="120px">
          <el-form-item label="书名" prop="bookName">
            <el-input v-model="addForm.bookName"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="bookAuthor">
            <el-input v-model="addForm.bookAuthor"></el-input>
          </el-form-item>
          <el-form-item label="图书馆">
            <el-radio-group v-model="addForm.bookLibrary">
              <el-radio-button value="南图">南图</el-radio-button>
              <el-radio-button value="北图">北图</el-radio-button>
              <el-radio-button value="教师之家">教师之家</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="addForm.bookType" placeholder="请选择">
              <el-option
                v-for="item in types"
                :key="item.TypeID"
                :label="item.TypeName"
                :value="item.TypeID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="位置" prop="bookLocation">
            <el-radio-group v-model="addForm.bookLocation">
              <el-radio-button value="馆藏区A">馆藏区A</el-radio-button>
              <el-radio-button value="馆藏区B">馆藏区B</el-radio-button>
              <el-radio-button value="馆藏区C">馆藏区C</el-radio-button>
              <el-radio-button value="馆藏区D">馆藏区D</el-radio-button>
              <el-radio-button value="馆藏区E">馆藏区E</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="状态" prop="bookStatus">
            <el-radio-group v-model="addForm.bookStatus">
              <el-radio value="1">已借出</el-radio>
              <el-radio value="0">未借出</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="书籍简介" prop="bookDescription">
            <el-input type="textarea" v-model="addForm.bookDescription"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addsBook">添加书籍</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, resolveDynamicComponent } from "vue";
import {
  getBooksList,
  addBook,
  removeBook,
  alterBook,
  getOneBook,
  delAllBook,
  ExportAllBook,
  getSimpleBookTypeLis,
} from "../../api/api";
import * as XLSX from "xlsx";
//获取表格实例
let tableRef = ref(null);
//全部删除
let AllRemove = ref(false);
//删除
let removeRow = ref(null);
//图书列表
const tableData = ref();
//修改对话框是否可见
const editDialogVisible = ref(false);
//修改对话框内容
const editForm = reactive({
  bookName: "",
  bookAuthor: "",
  bookLibrary: "南图",
  bookType: "",
  bookLocation: "",
  bookStatus: "",
  bookDescription: "",
  bookNumber: null,
});
////修改对话框规则
const editFormRules = {
  BookName: [{ required: true, message: "图书名称不能为空", trigger: "blur" }],
  BookAuthor: [{ required: true, message: "图书作者不能为空", trigger: "blur" }],
  BookLocation: [{ required: true, message: "图书位置不能为空", trigger: "blur" }],
  BookDescription: [{ required: true, message: "图书介绍不能为空", trigger: "blur" }],
};
//增加对话框是否可见
const addDialogVisible = ref(false);
//增加对话框内容
const addForm = reactive({
  bookName: "",
  bookAuthor: "",
  bookLibrary: "南图",
  bookType: "",
  bookLocation: "馆藏区A",
  bookStatus: "在馆",
  bookDescription: "",
});
//增加对话框规则
const addFormRules = {
  bookName: [{ required: true, message: "图书名称不能为空", trigger: "blur" }],
  bookAuthor: [{ required: true, message: "图书作者不能为空", trigger: "blur" }],
  bookDescription: [{ required: true, message: "图书介绍不能为空", trigger: "blur" }],
};
//下拉框列表
const searchs = [
  {
    value: "book_number",
    label: "图书编号",
  },
  {
    value: "book_name",
    label: "书名",
  },
  {
    value: "book_author",
    label: "作者",
  },
  {
    value: "book_library",
    label: "图书馆",
  },
  {
    value: "book_location",
    label: "位置",
  },
  {
    value: "book_status",
    label: "状态",
  },
  {
    value: "book_description",
    label: "描述",
  },
];
//翻页
const queryInfo = reactive({
  pageNum: 1,
  size: 5,
  condition: "",
  query: "",
});
//书籍总数
const total = ref(0);
//增加书籍时的书籍分类
let types = [
  {
    TypeID: "童话",
    TypeName: "童话",
  },
  {
    TypeID: "文学",
    TypeName: "文学",
  },
  {
    TypeID: "散文",
    TypeName: "散文",
  },
];
const title = "书籍管理";
const json_fields = {
  图书编号: "bookNumber",
  图书名称: "bookName",
  作者: "bookAuthor",
  图书馆: "bookLibrary",
  分类: "bookType",
  位置: "bookLocation",
  状态: "bookStatus",
  描述: "bookDescription",
};
const loading = ref(true);
//多选框
const multipleSelection = ref([]);
//上传
const fileList = ref([]);

onMounted(() => {
  getBookList();
  getBookType();
  // 确保 tableRef 已被赋值
  if (tableRef.value) {
    const rows = tableRef.value.getSelectionRows();
    console.log("Selected rows on mount:", rows);
  } else {
    console.log("tableRef is null on mounted");
  }
});

watch(
  () => tableRef.value && tableRef.value.getSelectionRows(),
  (newRows, oldRows) => {
    if (newRows) {
      const selectRow = newRows.map(item => item.BookID);
      removeRow.value = selectRow;
      console.log(removeRow.value);
    }
  },
  { immediate: true } // 这样在监听开始时也会执行一次回调
);

//导出excel
const exportToExcel = () => {
  //excel表格头部
  const headers = ["图书馆编号", "图书名称", "作者", "图书馆", "分类", "位置", "状态", "描述"];
  // 转换表格数据为数组
  const ExcleData = tableData.value.map(item => [
    item.BookNumber,
    item.BookName,
    item.BookAuthor,
    item.BookLibrary,
    item.BookType,
    item.bookLocation,
    item.bookStatus,
    item.bookDescription,
  ]);
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();
  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet([headers, ...ExcleData]);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  // 生成Excel文件
  XLSX.writeFile(workbook, "图书查询表格.xls");
};

//导出所有图书
const exportToAll = () => {
  let data = { condition: "", query: "" };
  (data.condition = queryInfo.condition), (data.query = queryInfo.query);
  console.log(data);
  ExportAllBook(data)
    .then(res => console.log(res))
    .catch(res => console.log(res));
};
//获取所有的类型
const getBookType = () => {
  getSimpleBookTypeLis()
    .then(res => {
      (types = res.data), console.log(types), console.log(res);
    })
    .catch(err => console.log(err));
};

//一页几个
const handleSizeChange = val => {
  queryInfo.size = val;
  getBookList();
};
//翻页
const handleCurrentChange = val => {
  queryInfo.pageNum = val;
  getBookList();
};
const handleSelectionChange = val => {
  multipleSelection.value = val;
};

//让修改图书的对话框可见,回显数据
const showEditDialog = id => {
  editDialogVisible.value = true;
  // 发送axios请求 获取数据库中的书籍分类信息
  let bookid = id;
  getOneBook(bookid)
    .then(res => {
      (editForm.bookName = res.data.BookName),
        (editForm.bookAuthor = res.data.BookAuthor),
        (editForm.bookLibrary = res.data.BookLibrary),
        (editForm.bookType = res.data.BookType),
        (editForm.bookLocation = res.data.BookLocation),
        (editForm.bookStatus = res.data.BookStatus),
        (editForm.bookDescription = res.data.BookDescription),
        (editForm.bookNumber = res.data.BookNumber);
      console.log(editForm, "111");
      ElMessage({
        message: "获取信息成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });
  // 让修改公告的对话框可见
};
//监听修改对话框的关闭，一旦对话框关闭，就重置表单，回显数据
const editDialogClosed = () => {
  //   $refs.editFormRef.resetFields();
};
//删除单个图书
const removeUserById = id => {
  removeBook(id)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    })
    .then(res => getBookList())
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("删除失败");
    });
};
//监听添加公告对话框的关闭，一旦对话框关闭，就重置表单
const addDialogClosed = () => {
  //   $refs.addFormRef.resetFields();
};

//当用户点击发送新公告时，让添加对话框的visible改为true
const showAddDialog = () => {
  // // 发送axios请求 获取数据库中的书籍分类信息
  // const { data: res } = await  $http.get("admin/get_type");
  // console.log(res);
  // if (res.status !== 200) {
  //   return  $message.error(res.msg);
  // }
  //  types = res.data;
  addDialogVisible.value = true;
};
//获取图书列表
const getBookList = () => {
  loading.value = true;
  getBooksList(queryInfo)
    .then(res => {
      tableData.value = res.data.records;
      total.value = parseInt(res.data.total);
      console.log(tableData.value, "111");
      ElMessage({
        message: "获取信息成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });
  loading.value = false;
};
//添加图书
const addsBook = () => {
  addBook(addForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "增加书籍成功",
        type: "success",
      });
    })
    .then(res => {
      getBookList();
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("增加书籍失败");
    });

  addDialogVisible.value = false;
};
//修改图书
const updateBook = () => {
  alterBook(editForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "修改信息成功",
        type: "success",
      });
    })
    .then(res => {
      getBookList();
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("修改信息失败");
    });

  editDialogVisible.value = false;
};
const downLoad = () => {
  getPdf(title);
};
const fullScreen = () => {
  // Dom对象的一个属性: 可以用来判断当前是否为全屏模式(trueORfalse)
  let full = document.fullscreenElement;
  // 切换为全屏模式
  if (!full) {
    // 文档根节点的方法requestFullscreen实现全屏模式
    document.documentElement.requestFullscreen();
  } else {
    // 退出全屏模式
    document.exitFullscreen();
  }
};
// 批量删除图书
const removeBatch = () => {
  const data = {
    bookIds: removeRow.value,
  };
  delAllBook(data)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    })
    // // 防止删除出现数据显示错误
    .then(res => {
      queryInfo.pageNum = 1;
      queryInfo.size = 5;
      getBookList();
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("删除失败");
    });
  AllRemove.value = false;
};
const submitUpload = () => {
  console.log($refs.upload.data);
  $refs.upload.submit();
  $message.success({
    duration: 1500,
    message: "Excel批量导入图书成功",
  });
};
const handleRemove = (file, fileList) => {
  // console.log(file, fileList);
};
const handlePreview = file => {
  // console.log(file);
};
const onSuccess = (response, file, fileList) => {
  // console.log(response);
  // console.log(file);
  // console.log(fileList);
};
</script>

<style scoped></style>
